<template>
	<view class="publishJob">
		<view class="publishJob-content">
			<uni-forms ref="valiForm" :rules="rules" :modelValue="valiFormData">
				<view class="formLabel no-border uni-flex">
					<text>技能证书</text>
					<uni-forms-item required name="name">
						<uni-easyinput class="my-input" v-model="valiFormData.name" placeholder="请输入证书名称" />
					</uni-forms-item>
				</view>
				<view class="imgBox">
					<uni-file-picker title="添加图片" v-model="imageValue" fileMediatype="image" mode="grid" limit="5"
						@select="select" @progress="progress" @success="success" @fail="fail" />
				</view>
			</uni-forms>
		</view>
		<view class="fixed-bottom-buttons">
			<view class="uni-flex uni-align-center uni-justify-between">
				<view class="button publish-job" @click="cancel">取消</view>
				<view class="button publish-demand" @click="save">保存</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		qiNiuFileUpload
	} from "@/utils/qiniu.js";
	export default {
		data() {
			return {
				userid: '',
				imageValue: [], // 存储选择的图片
				uploadedImages: [], // 存储上传成功的图片key
				tempImagePaths: [], // 存储临时图片路径
				isChecked: false,
				// 校验表单数据
				valiFormData: {
					name: '',
				},
				// 校验规则
				rules: {
					name: {
						rules: [{
							required: true,
							errorMessage: '证书名称不能为空'
						}]
					}
				},
			}
		},
		mounted() {
			const userinfo = uni.getStorageSync("user_info");
			if (userinfo) {
				this.userid = JSON.parse(userinfo).id;
			}
		},
		methods: {
			select(e) {
				this.imageValue = e.tempFiles;
				// 保存临时图片路径
				this.tempImagePaths = e.tempFiles.map(file => file.path);
			},
			// 上传图片方法
			uploadImages() {
				return new Promise((resolve, reject) => {
					if (this.imageValue.length === 0) {
						uni.showToast({
							title: '请先选择图片',
							icon: 'none'
						});
						reject('请先选择图片');
						return;
					}

					const timestamp = Date.now();
					const filePaths = this.imageValue.map((file, index) => ({
						path: file.path,
						key: `images/cert/${this.userid}/${timestamp}_${index+1}.${file.ext || 'png'}`
					}));
					console.log('filePaths', filePaths);

					qiNiuFileUpload(
						filePaths,
						(keys) => {
							this.uploadedImages = keys.split(',');
							uni.showToast({
								title: '图片上传成功',
								icon: 'success'
							});
							resolve(keys);
						},
						(error) => {
							console.error('上传失败:', error);
							uni.showToast({
								title: '部分图片上传失败',
								icon: 'none'
							});
							reject(error);
						}
					);
				});
			},
			progress(e) {
				console.log('上传进度：', e)
			},
			success(e) {
				console.log('上传成功')
			},
			fail(e) {
				console.log('上传失败：', e)
			},
			cancel() {
				uni.navigateBack({
					delta: 1
				});
			},
			async save() {
				try {
					// 1. 表单验证
					await this.$refs.valiForm.validate();

					// 2. 上传图片（获取正式URL）
					await this.uploadImages();

					// 3. 准备临时数据（包含临时路径和正式路径）
					const tempCert = {
						id: `temp_${Date.now()}`, // 临时ID
						certType: this.valiFormData.name,
						imgFullUrls: this.uploadedImages.join(','), // 正式路径（用于提交后台）
						tempImgUrls: this.tempImagePaths.join(','), // 临时路径（用于前端展示）
						createBy: this.valiFormData.name,
						isTemp: true // 标记为临时数据
					};

					// 4. 通过事件通知上一页
					const eventChannel = this.getOpenerEventChannel();
					eventChannel.emit('certSaved', {
						cert: tempCert
					});

					uni.showToast({
						title: '保存成功',
						icon: 'success'
					});
					setTimeout(() => uni.navigateBack(), 1500);
				} catch (err) {
					console.log('保存失败:', err);
					uni.showToast({
						title: err.message || '保存失败',
						icon: 'none'
					});
				}
			}
		}
	}
</script>

<style scoped lang="scss">
	/* 样式保持不变 */
	.publishJob {
		padding: 26rpx 24rpx 0;
		background: #F5F5F5;
		min-height: calc(100vh - 26rpx);
		position: relative;

		.publishJob-content {
			background: #FFFFFF;
			border-radius: 20rpx;
			padding: 34rpx 26rpx 0 23rpx;
			min-height: calc(100vh - 250rpx);

			.imgBox {
				margin: 20rpx 0 0 150rpx;
			}

			.formLabel {
				text {
					font-weight: 500;
					font-size: 28rpx;
					color: #303133;
					line-height: 80rpx;
				}
			}
		}

		.fixed-bottom-buttons {
			position: fixed;
			bottom: 0;
			left: 0;
			right: 0;
			height: 154rpx;
			background: #ffffff;
			padding: 12rpx 23rpx 0;

			.button {
				flex: 1;
				display: flex;
				align-items: center;
				justify-content: center;
				font-size: 32rpx;
				color: #ffffff;

				&.publish-job {
					height: 88rpx;
					background: #fff;
					border-radius: 44rpx;
					margin-right: 61rpx;
					font-weight: 600;
					font-size: 30rpx;
					color: #666666;
					line-height: 88rpx;
					border: 1px solid #666;
				}

				&.publish-demand {
					height: 88rpx;
					background: #2f80ed;
					border-radius: 44rpx;
					font-weight: 600;
					font-size: 30rpx;
					color: #ffffff;
					line-height: 88rpx;
				}
			}
		}
	}
</style>